package cn.com.utt.common.protorpc;

import com.google.protobuf.Message;

import cn.com.utt.common.protorpc.codec.MessageDecoder;
import cn.com.utt.common.protorpc.message.Callback;
import cn.com.utt.common.protorpc.message.RPCMessage;
import cn.com.utt.common.protorpc.proto.ArgProto;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;

public class HeartbeatHandler extends ChannelInboundHandlerAdapter{
	private static String pingServiceMethod = "protorpc.Ping";
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		if (evt instanceof IdleStateEvent){
			//System.out.println("ping...");
			//send ping
			//ctx.writeAndFlush(msg);
			//ctx.channel().t
			//client.callBlockingMethod(pingServiceMethod,null,null);
			MessageDecoder decoder = (MessageDecoder) ctx.pipeline().get("messageDecoder");
			long nextSeqId = decoder.getNextSeqId();
			RPCMessage heartbeat = buildRequest(pingServiceMethod, nextSeqId, null);
			Callback callback = new Callback(null, null);
			decoder.registerCallback(nextSeqId, callback);
			ctx.writeAndFlush(heartbeat).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
			//RPCMessage hb = buildHeartbeat();
			//client.callMethod(pingServiceMethod, null, null);
			//ctx.writeAndFlush(hb);
		}else{
			super.userEventTriggered(ctx, evt);
		}
	}
	
	private RPCMessage buildRequest(String serviceMethod, long seqId,
			Message request) {
		RPCMessage msg = new RPCMessage();
		ArgProto.Arg.Builder reqBuilder = ArgProto.Arg
				.newBuilder();
		reqBuilder.setSeq(seqId);
		reqBuilder.setServiceMethod(serviceMethod);
		ArgProto.Arg header = reqBuilder.build();
		msg.setHeader(header);
		msg.setBody(request);
		return msg;
	}

}
